﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Text;

namespace SP_XHWeb.ControlTemplates.SP_XHWeb
{
    public partial class LeftMenu : UserControl
    {
        private string AbsolutePath = string.Empty;
        private string AbsoluteUri = string.Empty;
        private string SiteTitle = string.Empty;
        private string RawUrl = string.Empty;
        public string sitename = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string listUrl = Request.Url.ToString();
            AbsolutePath = this.Page.Request.Url.AbsolutePath.ToLower();
            AbsoluteUri = this.Page.Request.Url.AbsoluteUri.ToLower();
            RawUrl = this.Page.Request.RawUrl.ToLower();

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(listUrl))
                {
                    using (SPSite site = new SPSite(listUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList spList = web.Lists.TryGetList("SiteMapList");
                            if (RawUrl.StartsWith("/companyinfo"))
                            {
                                SiteTitle = "公司信息";
                                sitename = "/companyinfo";
                            }
                            else if (RawUrl.StartsWith("/projectinfo"))
                            {
                                SiteTitle = "项目信息";
                                sitename = "/projectinfo";
                                //三级项目页面菜单加载
                                InitLeftMenu();
                            }
                            else if (RawUrl.StartsWith("/infomationcenter"))
                            {
                                SiteTitle = "资讯中心";
                                sitename = "/infomationcenter";
                            }
                            else if (RawUrl.StartsWith("/enterpriseculture"))
                            {
                                SiteTitle = "企业文化";
                                sitename = "/enterpriseculture";
                            }
                            else if (RawUrl.StartsWith("/knowledgecenter"))
                            {
                                SiteTitle = "知识中心";
                                sitename = "/knowledgecenter";
                            }
                            else if (RawUrl.StartsWith("/_layouts/sp_xhweb/employeedetails.aspx"))
                            {
                                SiteTitle = "公司信息";
                            }
                            else
                            {
                                SiteTitle = "星浩资本";
                                sitename = "/default.aspx";
                            }

                            lblDivHtml.InnerHtml = GetLinks(spList);

                            //if (spList != null)
                            //{
                            //    List<MySpaceLink> list = GetLinks(spList);
                            //    LeftMenuList.DataSource = list;
                            //    LeftMenuList.DataBind();
                            //}

                        }
                    }
                }
            }
        }


        private string GetLinks(SPList spList)
        {
            StringBuilder divhtml = new StringBuilder();
            divhtml.Append("<div class='page_main_left'>");
            divhtml.Append("<ul>");
            divhtml.Append("<li id='dl'>" + SiteTitle + "</li>");

            List<MySpaceLink> list = new List<MySpaceLink>();
            List<SPListItem> itemlist = new List<SPListItem>();
            string hostUrl = this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority;

            //using (SPSite site = new SPSite(hostUrl+sitename))
            //{
            //    using (SPWeb web = site.OpenWeb())
            //    {
            //        spList = web.Lists.TryGetList("SiteMapList");

            if (RawUrl.StartsWith("/_layouts/sp_xhweb/employeedetails.aspx"))
            {
                using (SPSite site = new SPSite(hostUrl + "/companyinfo"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        spList = web.Lists.TryGetList("SiteMapList");
                    }
                }
            }

            if (spList != null && spList.ItemCount != 0)
            {
                int count = 0;
                foreach (SPListItem item in spList.Items)
                {
                    if (item["UrlAddress"] != null && !string.IsNullOrEmpty(item["UrlAddress"].ToString()))
                    {
                        //查找根节点（ParentID==0）
                        if (item["ParentID"] != null && !string.IsNullOrEmpty(item["ParentID"].ToString()) && item["ParentID"].ToString() == "0")
                        {
                            itemlist.Add(item);
                            count++;
                        }
                    }
                }


                //拼接导航菜单
                if (itemlist != null && itemlist.Count != 0)
                {
                    for (int i = 0; i < itemlist.Count; i++)
                    {
                        string urltitle = itemlist[i]["UrlAddress"].ToString().Substring(itemlist[i]["UrlAddress"].ToString().LastIndexOf("/") + 1, itemlist[i]["UrlAddress"].ToString().LastIndexOf(".") - itemlist[i]["UrlAddress"].ToString().LastIndexOf("/") - 1);
                        //加载根节点
                        if (this.AbsolutePath.StartsWith(itemlist[i]["UrlAddress"].ToString().ToLower()))
                        {
                            divhtml.Append("<li class='dq'><a href=" + itemlist[i]["UrlAddress"].ToString() + ">" + itemlist[i].Title + "</a></li>");
                        }
                        else
                        {
                            divhtml.Append("<li class='" + urltitle + "_Selection'><a href=" + itemlist[i]["UrlAddress"].ToString() + ">" + itemlist[i].Title + "</a></li>");
                        }


                        divhtml.AppendFormat("<ul style='padding:0; margin:0; font-weight:normal; display:none;' class='{0}'>", urltitle + "_ChildMenu");
                        //遍历根节点下的子节点
                        foreach (SPListItem item in spList.Items)
                        {
                            if (item["UrlAddress"] != null && !string.IsNullOrEmpty(item["UrlAddress"].ToString()))
                            {
                                if (item["ParentID"] != null && !string.IsNullOrEmpty(item["ParentID"].ToString()) && item["ParentID"].ToString() == itemlist[i]["MapID"].ToString())
                                {

                                    if (this.AbsolutePath.StartsWith(item["UrlAddress"].ToString().ToLower()))
                                    {

                                        divhtml.Append("<li style='padding:0; margin:0; float:left; background:#f6f4f0;'>");
                                        divhtml.Append("<a style=' font-weight:bold; background:url(/_layouts/images/SP_XHWeb/sj01.gif) no-repeat left; background-position:25px 9px; padding:0 0 0 33px;' href=" + item["UrlAddress"].ToString() + ">" + item.Title + "</a>");
                                        divhtml.Append("</li>");
                                    }
                                    else
                                    {
                                        divhtml.Append("<li style='padding:0; margin:0; float:left; background:#f6f4f0;'>");
                                        divhtml.Append("<a style=' background:url(/_layouts/images/SP_XHWeb/sj01.gif) no-repeat left; background-position:25px 9px; padding:0 0 0 33px;' href=" + item["UrlAddress"].ToString() + ">" + item.Title + "</a>");
                                        divhtml.Append("</li>");
                                    }

                                }
                            }
                        }
                        divhtml.Append("</ul>");
                    }
                    //    }
                    //}
                }
            }
            divhtml.Append("</ul>");
            divhtml.Append("</div>");

            divhtml.Append("<style>");
            //拼接导航子菜单样式
            if (spList != null && spList.ItemCount != 0)
            {
                foreach (SPListItem item in spList.Items)
                {
                    if (item["UrlAddress"] != null && !string.IsNullOrEmpty(item["UrlAddress"].ToString()))
                    {
                        if (item["ParentID"] != null && !string.IsNullOrEmpty(item["ParentID"].ToString()) && item["ParentID"].ToString() != "0")
                        {
                            //查找与URL相同的子节点
                            if (this.AbsolutePath.StartsWith(item["UrlAddress"].ToString().ToLower()))
                            {
                                //查找父节点URL
                                string urlstr = "";
                                for (int i = 0; i < itemlist.Count; i++)
                                {
                                    if (itemlist[i]["MapID"].ToString() == item["ParentID"].ToString())
                                    {
                                        urlstr = itemlist[i]["UrlAddress"].ToString();
                                    }
                                }
                                if (urlstr != "")
                                {
                                    string classtitle = urlstr.Substring(urlstr.LastIndexOf("/") + 1, urlstr.LastIndexOf(".") - urlstr.LastIndexOf("/") - 1);
                                    divhtml.AppendFormat(".{0}", classtitle + "_ChildMenu");
                                    divhtml.Append("{");
                                    divhtml.Append("display:block !important;");
                                    divhtml.Append("}");

                                    divhtml.AppendFormat(".{0}", classtitle + "_Selection");
                                    divhtml.Append("{");
                                    divhtml.Append("width:147px; min-height:24px;_height:24px; line-height:24px; float:left; font-weight:bold; background:url(/_layouts/images/SP_XHWeb/left-tit02.gif) no-repeat !important;");
                                    divhtml.Append("}");
                                }
                            }
                        }
                        //else
                        //{
                        //    string classtitle = item["UrlAddress"].ToString().Substring(item["UrlAddress"].ToString().LastIndexOf("/") + 1, item["UrlAddress"].ToString().LastIndexOf(".") - item["UrlAddress"].ToString().LastIndexOf("/") - 1);
                        //    divhtml.AppendFormat(".{0}", classtitle + "_ChildMenu");
                        //    divhtml.Append("{");
                        //    divhtml.Append("display:none;");
                        //    divhtml.Append("}");
                        //}
                    }
                }
            }
            divhtml.Append("</style>");

            return divhtml.ToString();
        }


        //创建项目信息时使用该方法
        //使用时需要判断是否为新建项目信息
        private void InitLeftMenu()
        {
            string siteUrl = this.Page.Request.Url.ToString().ToLower();
            string absolPath = this.Page.Request.Url.AbsolutePath.ToLower();
            string absolUrl = this.Page.Request.Url.AbsoluteUri.ToLower();
            string[] str = absolPath.Substring(1).Split('/');

            if (str != null && str.Length == 3 && str[0] == "projectinfo" && str[1] != "" && str[2] == "default.aspx")
            {
                if (!string.IsNullOrEmpty(siteUrl))
                {
                    using (SPSite site = new SPSite(siteUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            try
                            {
                                SPListCollection lists = web.Lists;
                                SPList mapList = lists.TryGetList("SiteMapList");
                                //允许站点在get请求下进行更新
                                web.AllowUnsafeUpdates = true;
                                if (mapList != null)
                                {
                                    if (mapList.ItemCount != 0)
                                    {
                                        foreach (SPListItem item in mapList.Items)
                                        {
                                            if (item["UrlAddress"] != null && !string.IsNullOrEmpty(item["UrlAddress"].ToString()))
                                            {
                                                if (!item["UrlAddress"].ToString().ToLower().StartsWith("/projectinfo/" + str[1] + "/"))
                                                {
                                                    if (item.Title == "项目首页")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/default.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "项目介绍")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/introduction.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "项目资讯")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/information.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "组织结构")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/organization.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "员工介绍")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/employee.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "项目通知及公告")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/notice.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "项目文档")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/document.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "员工活动")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/activity.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "号外")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/extra.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "职位空缺")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/job.aspx";
                                                        item.Update();
                                                    }
                                                    else if (item.Title == "学习与发展")
                                                    {
                                                        item["UrlAddress"] = "/projectinfo/" + str[1] + "/pages/study.aspx";
                                                        item.Update();
                                                    }

                                                }
                                            }
                                            else
                                            {
                                                mapList.Delete();
                                                CreateSiteMapList(web, lists, str[1]);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        mapList.Delete();
                                        CreateSiteMapList(web, lists, str[1]);
                                    }

                                }
                                else
                                {
                                    CreateSiteMapList(web, lists, str[1]);
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }

        //创建新的SiteMapList
        private void CreateSiteMapList(SPWeb web, SPListCollection lists, string str)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPList newList = web.Lists[lists.Add("SiteMapList", "SiteMapList", SPListTemplateType.GenericList)];

                if (newList != null)
                {
                    newList.Fields.Add("MapID", SPFieldType.Number, false);
                    newList.Fields.Add("ParentID", SPFieldType.Number, false);
                    newList.Fields.Add("UrlAddress", SPFieldType.Text, false);
                    newList.OnQuickLaunch = false;
                    newList.Update();

                    //item.Title为只读，无法赋值
                    //英文版需要用item["Title"]赋值，中文版用item["标题"]
                    SPListItem item1 = newList.Items.Add();
                    try
                    {
                        item1["标题"] = "项目首页";
                    }
                    catch
                    {
                        item1["Title"] = "项目首页";
                    }
                    item1["MapID"] = 1;
                    item1["ParentID"] = 0;
                    item1["UrlAddress"] = "/projectinfo/" + str + "/default.aspx";
                    item1.Update();

                    SPListItem item2 = newList.Items.Add();
                    try
                    {
                        item2["标题"] = "项目介绍";
                    }
                    catch
                    {
                        item2["Title"] = "项目介绍";
                    }
                    item2["MapID"] = 2;
                    item2["ParentID"] = 0;
                    item2["UrlAddress"] = "/projectinfo/" + str + "/pages/introduction.aspx";
                    item2.Update();

                    SPListItem item3 = newList.Items.Add();
                    try
                    {
                        item3["标题"] = "项目资讯";
                    }
                    catch
                    {
                        item3["Title"] = "项目资讯";
                    }
                    item3["MapID"] = 3;
                    item3["ParentID"] = 0;
                    item3["UrlAddress"] = "/projectinfo/" + str + "/pages/information.aspx";
                    item3.Update();

                    SPListItem item4 = newList.Items.Add();
                    try
                    {
                        item4["标题"] = "组织结构";
                    }
                    catch
                    {
                        item4["Title"] = "组织结构";
                    }
                    item4["MapID"] = 4;
                    item4["ParentID"] = 0;
                    item4["UrlAddress"] = "/projectinfo/" + str + "/pages/organization.aspx";
                    item4.Update();

                    SPListItem item5 = newList.Items.Add();
                    try
                    {
                        item5["标题"] = "员工介绍";
                    }
                    catch
                    {
                        item5["Title"] = "员工介绍";
                    }
                    item5["MapID"] = 5;
                    item5["ParentID"] = 0;
                    item5["UrlAddress"] = "/projectinfo/" + str + "/pages/employee.aspx";
                    item5.Update();

                    SPListItem item6 = newList.Items.Add();
                    try
                    {
                        item6["标题"] = "项目通知及公告";
                    }
                    catch
                    {
                        item6["Title"] = "项目通知及公告";
                    }
                    item6["MapID"] = 6;
                    item6["ParentID"] = 0;
                    item6["UrlAddress"] = "/projectinfo/" + str + "/pages/notice.aspx";
                    item6.Update();

                    SPListItem item7 = newList.Items.Add();
                    try
                    {
                        item7["标题"] = "项目文档";
                    }
                    catch
                    {
                        item7["Title"] = "项目文档";
                    }
                    item7["MapID"] = 7;
                    item7["ParentID"] = 0;
                    item7["UrlAddress"] = "/projectinfo/" + str + "/pages/document.aspx";
                    item7.Update();

                    SPListItem item8 = newList.Items.Add();
                    try
                    {
                        item8["标题"] = "员工活动";
                    }
                    catch
                    {
                        item8["Title"] = "员工活动";
                    }
                    item8["MapID"] = 8;
                    item8["ParentID"] = 0;
                    item8["UrlAddress"] = "/projectinfo/" + str + "/pages/activity.aspx";
                    item8.Update();

                    SPListItem item9 = newList.Items.Add();
                    try
                    {
                        item9["标题"] = "号外";
                    }
                    catch
                    {
                        item9["Title"] = "号外";
                    }
                    item9["MapID"] = 9;
                    item9["ParentID"] = 0;
                    item9["UrlAddress"] = "/projectinfo/" + str + "/pages/extra.aspx";
                    item9.Update();

                    SPListItem item10 = newList.Items.Add();
                    try
                    {
                        item10["标题"] = "职位空缺";
                    }
                    catch
                    {
                        item10["Title"] = "职位空缺";
                    }
                    item10["MapID"] = 10;
                    item10["ParentID"] = 0;
                    item10["UrlAddress"] = "/projectinfo/" + str + "/pages/job.aspx";
                    item10.Update();

                    SPListItem item11 = newList.Items.Add();
                    try
                    {
                        item11["标题"] = "学习与发展";
                    }
                    catch
                    {
                        item11["Title"] = "学习与发展";
                    }
                    item11["MapID"] = 11;
                    item11["ParentID"] = 0;
                    item11["UrlAddress"] = "/projectinfo/" + str + "/pages/study.aspx";
                    item11.Update();


                }
            });
        }

    }

    public class MySpaceLink
    {
        public string Title { get; set; }

        public string Url { get; set; }

        public int Order { get; set; }

        public bool IsCurrentPage { get; set; }

        public string MapID { get; set; }

        public MySpaceLink(string title, string url, int order, bool isCurrentPage, string mapID)
        {
            this.Title = title;
            this.Url = url;
            this.Order = order;
            this.IsCurrentPage = isCurrentPage;
            this.MapID = mapID;
        }
    }
}
